package com.erik.ipmonitor.parse;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.File;

public class ExtractLocFromSitemap {


    public static void main(String[] args) {
        parseSitemap();
    }


    /**
     * 解析sitemap
     */
    private static void parseSitemap() {
        try {
            // 创建文档解析工厂和解析器
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();

            // 解析XML文件（请替换为你的XML文件路径）
            Document document = builder.parse(new File("C:\\Users\\zhou\\Downloads\\sitemap_of_Blogs.xml"));
            document.getDocumentElement().normalize();

            // 获取所有url节点
            NodeList urlList = document.getElementsByTagName("url");
            // 遍历每个url节点，提取loc内容
            for (int i = 0; i < urlList.getLength(); i++) {
                Node urlNode = urlList.item(i);
                if (urlNode.getNodeType() == Node.ELEMENT_NODE) {
                    Element urlElement = (Element) urlNode;
                    // 提取loc元素内容
                    NodeList locList = urlElement.getElementsByTagName("loc");
                    if (locList.getLength() > 0) {
                        String loc = locList.item(0).getTextContent();
                        System.out.println("URL #" + (i + 1) + ": " + loc);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
